package net.neptech.listener.impl;

import cn.hutool.log.StaticLog;
import lombok.extern.slf4j.Slf4j;
import net.neptech.model.dto.InstanceNodeRecordParamDto;
import net.neptech.listener.AbstractEventListenerStrategy;
import net.neptech.service.RemoteService;
import net.neptech.util.FlowableUtil;
import net.neptech.util.JsonUtil;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.event.impl.FlowableMultiInstanceActivityCompletedEventImpl;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author Saya
 * @Date 2025/8/22 14:56
 * @Description 多实例节点结束了
 **/
@Slf4j
@Component
public class MultiInstanceActivityCompletedEventListener extends AbstractEventListenerStrategy implements InitializingBean {
    
    @Autowired
    private RemoteService remoteService;
    @Autowired
    private RuntimeService runtimeService;
    /**
     * 处理数据
     */
    @Override
    public void handle(FlowableEvent event) {
        //多实例任务
        FlowableMultiInstanceActivityCompletedEventImpl flowableActivityEvent = (FlowableMultiInstanceActivityCompletedEventImpl) event;
        String activityId = flowableActivityEvent.getActivityId();
        String activityName = flowableActivityEvent.getActivityName();
        log.info("实例完成1 节点id：{} 名字:{}", activityId, activityName);
        String executionId = flowableActivityEvent.getExecutionId();
        Map<String, Object> variables = runtimeService.getVariables(executionId);
        String processInstanceId = flowableActivityEvent.getProcessInstanceId();
        String processDefinitionId = flowableActivityEvent.getProcessDefinitionId();
        String flowId = FlowableUtil.getFlowId(processDefinitionId);
        InstanceNodeRecordParamDto instanceNodeRecordParamDto = new InstanceNodeRecordParamDto();
        instanceNodeRecordParamDto.setFlowId(flowId);
        instanceNodeRecordParamDto.setExecutionId(executionId);
        instanceNodeRecordParamDto.setProcessInstanceId(processInstanceId);
        instanceNodeRecordParamDto.setData(JsonUtil.toJSONString(variables));
        instanceNodeRecordParamDto.setNodeId(activityId);
        instanceNodeRecordParamDto.setNodeName(activityName);
        remoteService.endNodeEvent(instanceNodeRecordParamDto);
        StaticLog.info("节点结束了： {} {}  {}",flowId,executionId,activityName);
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        afterPropertiesSet(FlowableEngineEventType.MULTI_INSTANCE_ACTIVITY_COMPLETED_WITH_CONDITION.toString());
        afterPropertiesSet(FlowableEngineEventType.MULTI_INSTANCE_ACTIVITY_COMPLETED.toString());
    }
}
